package com.simple.common.framework.scale;

import com.simple.common.framework.context.Contexts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author yasud
 * @date 2020年09月21日 11:50
 * @description
 */
@Component
@EnableConfigurationProperties(ScaleProperties.class)
public class Scale {

    @Autowired
    ScaleProperties scaleProperties;

    /**
     * 统一处理精度
     * @param amount
     * @return
     */
    public static BigDecimal scale(BigDecimal amount) {
        Scale scale = Contexts.BEANFACTORY.getBean(Scale.class);
        return scale.setScale(amount);
    }

    /**
     * 统一处理精度
     * @param amount
     * @return
     */
    public static BigDecimal scale(String amount) {
        if (StringUtils.isBlank(amount)) return null;
        Scale scale = Contexts.BEANFACTORY.getBean(Scale.class);
        return scale.setScale(new BigDecimal(amount));
    }

    /**
     * 统一处理精度
     * @param amount
     * @return
     */
    public static BigDecimal scale(Double amount) {
        Scale scale = Contexts.BEANFACTORY.getBean(Scale.class);
        return scale.setScale(BigDecimal.valueOf(amount));
    }


    public BigDecimal setScale(BigDecimal amount) {
        switch (scaleProperties.getType()) {
            case ROUND_UP:
                return amount.setScale(scaleProperties.getScale(), BigDecimal.ROUND_UP);
            case ROUND_DOWN:
                return amount.setScale(scaleProperties.getScale(), BigDecimal.ROUND_DOWN);
            case ROUND_HALF_UP:
            default:
                return amount.setScale(scaleProperties.getScale(), BigDecimal.ROUND_HALF_UP);
        }
    }
}
